package firedrop
{
    import C.unistd.sleep;
    import avmplus.Socket;
    import flash.utils.getTimer;
    
    public class Client
    {
        private var _socket:Socket;
        
        private var _refresh:uint = 1000; //ms
        
        private var _running:Boolean;
        
        public function Client()
        {
            _running = false;
            
            Socket.prototype.record = function() {};
            _socket = new Socket();
            
            _hookEvents();
        }
        
        private function _hookEvents():void
        {
            _socket.onConnect = this.onConnect;
            _socket.onDisconnect = this.onDisconnect;
            _socket.onDestruct   = this.onDestruct;
        }
        
        
        public function get address():String
        {
            if( _socket.local.indexOf(":") > 0 )
            {
                return _socket.local.split(":")[0];
            }
            
            return "";
        }
        
        public function get port():String
        {
            if( _socket.local.indexOf(":") > 0 )
            {
                return _socket.local.split(":")[1];
            }
            
            return "";
        }
        
        public function get connected():Boolean
        {
            return _socket.connected;
        }
        
        public function connect( address:String, port:uint ):void
        {
            _socket.connect( address, port );
        }
        
        public function onConnect():void
        {
            trace( "onConnect()" );
            
            _running = true;
            _start();
            
            _socket.send( "hello world\n" );
        }
        
        public function onDisconnect( message:String = "" ):void
        {
            trace( "onDisconnect( " + message + " )" );
            _running = false;
        }
        
        public function onDestruct():void
        {
            trace( "onDestruct()" );
        }
        
        public function onStart():void
        {
            trace( "Client started - " + address + ":" + port );
        }
        
        public function onStop():void
        {
            trace( "Client stoped" );
        }
        
        public function stop():void
        {
            _running = false;
        }
        
        private function _start():void
        {
            onStart();
            
            while( _running )
            {
                _loop();
                sleep( _refresh );
            }
            
            _stop();
        }
        
        private function _stop():void
        {
            _socket.close();
            
            onStop();
        }
        
        private function _loop():void
        {
            var data:String;
            
            if( _socket.readable ) //read data from server
            {
                
                try
                {
                    data = _socket.receiveAll();
                }
                catch( e:Error )
                {
                    //error receiving data from server
                    
                }
                
                if( !_socket.valid )
                {
                    //not valid connection
                    
                }
                else
                {
                    //valid connection
                    _interpret( data );
                }
            } //readable
            
            if( _socket.valid && _socket.writable )
            {
                //write data to server
                //				try
                //				{
                //					_socket.send( "CLIENT_" + getTimer() );
                //				}
                //				catch( e:Error )
                //				{
                //					//could not write to the server
                //				}
                
            } //writable
            
        }
        
        private function trim( source:String , chars:Array = null ):String
        {
            if( chars == null )
            {
                chars = ["\n","\r","\t"];
            }
            if ( source == null || source == "" )
            {
                return "" ;
            }
            
            var i:int , l:int ;
            
            ////// start
            
            l = source.length ;
            for( i = 0; (i < l) && (chars.indexOf( source.charAt( i ) ) > - 1) ; i++ )
            {
            }
            source = source.substring( i );
            
            ////// end
            
            l = source.length ;
            for( i = source.length - 1; (i >= 0) && (chars.indexOf( source.charAt( i ) ) > - 1) ; i-- )
            {
            }
            source = source.substring( 0, i + 1 ) ;
            
            ////// 
            
            return source ;
        }
        
        private function _interpret( message:String ):void
        {
            message = trim( message );
            trace( "message = \"" + message + "\"" );
            
        }
        
        
    }
}